<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wellcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片显示区域 -->
    <el-card >
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" @clear="getUserList()" clearable>
            <el-button @click="getUserInfo()" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" plain @click="addDialogVisible = true">添 加 用 户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" stripe style="width: 100%">
        <el-table-column
          type="index" width="50">
        </el-table-column>
        <el-table-column
          prop="username" label="姓名" width="150">
        </el-table-column>
        <el-table-column
          prop="email" label="邮箱" width="150">
        </el-table-column>
        <el-table-column
          prop="mobile" label="电话" width="150">
        </el-table-column>
        <el-table-column
          prop="role_name" label="角色" width="150">
        </el-table-column>
        <el-table-column label="状态" width="150">
          <template v-slot:default="slot">
            <!-- {{slot.row}} -->
            <el-switch v-model="slot.row.mg_state" @change="userStateChange(slot.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot:default="slot">
            <el-tooltip content="修改" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="updateUser(slot.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="delUser(slot.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="fenUser(slot.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 用户添加弹窗 -->
    <el-dialog 
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="35%"
      center
      :modal="false" :close-on-click-modal="false" @close="addDialogClose">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="70px" label-position="left">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户修改弹窗 -->
    <el-dialog 
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="35%"
      center
      :modal="false" :close-on-click-modal="false" @close="editDialogClose">
      <el-form :model="editForm" :rules="addRules" ref="editFormRef" label-width="70px" label-position="left">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的弹框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="roleDialogVisible"
      width="30%" :modal-append-to-body="false"
      center @close="roleDialogClose()">
      <div>
        <p>当前的角色：{{userInfo.username}}</p>
        <p>当前的用户：{{userInfo.role_name}}</p>
        <p>分配新的角色：
          <el-select v-model="selectRoleid" clearable placeholder="请选择">
            <el-option
              v-for="item in roleslist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name:'Wellcome',
  data(){
    return {
      queryInfo:{
        query:'',
        pagenum:1,
        pagesize:2,
      },
      userList:[],
      total:0,
      addDialogVisible:false,
      // 用户添加的表单数据
      addForm:{
        username:'',
        password:'',
        mobile:'',
        email:''
      },
      // 表单验证规则
      addRules:{
         username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password:{ required: true, message: '请输入密码', trigger: 'blur' },
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {  min: 11, max: 11, message: '长度为11个数字', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]
      },
      editDialogVisible:false,
      editForm:{},
      roleDialogVisible:false,
      userInfo:{},
      roleslist:[],
      selectRoleid:''
    }
  },
  created(){
    this.getUserList();
  },
  methods:{
    async getUserList(){
      const res = await this.axios.get('users',{params:this.queryInfo});
      // console.log(res.data);
      const {data} = res.data;
      // console.log(data);
      const {msg,status} = res.data.meta;
      // console.log(msg,status);
      if(status !== 200) this.$message.error(msg);
      this.userList = data.users;
      this.total = data.total;
      // console.log(data.total);
    },
    // 监听pagesize的改变
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    // 监听页码值的变化
    handleCurrentChange(val) {
      // console.log(val)
      // console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    // 监听用户状态改变
    async userStateChange(u){
      // console.log(u);
      const res = await this.axios.put(`users/${u.id}/state/${u.mg_state}`)
      // console.log(res.data);
      // const {data} = res.data;
      const {msg,status} = res.data.meta;
      if(status !== 200){
        u.mg_state = !u.mg_state;
        return this.$message.error(msg)
      }
      this.$message.success('用户状态修改成功~')
    },
    // 搜索用户信息
    getUserInfo(){
      if(!this.queryInfo.query){
        this.$message.error('输入不能为空哦~');
        return;
      }
      this.getUserList();
    },
    // 添加用户对话框关闭事件
    addDialogClose(){
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser(){
      this.$refs.addFormRef.validate(async valid =>{
        // console.log(valid);
        if(!valid) return;
        const res = await this.axios.post('users',this.addForm);
        // console.log(res);
        const {status} = res.data.meta;
        if(status !== 201) return this.$message.error('添加用户失败');
        this.$message.success('添加用户成功~');
        this.addDialogVisible = false;
        this.getUserList()
      })
    },
    // 修改用户
    async updateUser(id){
      const res  = await this.axios.get(`users/${id}`)
      // console.log(res);
      const {data} = res.data;
      const {status} = res.data.meta;
      if(status!==200) return this.$message.error('获取用户信息失败了');
      this.editForm = data;
      this.editDialogVisible = true;
    },
    // 修改用户对话框关闭事件
    editDialogClose(){
      this.$refs.editFormRef.resetFields()
    },
    // 提交用户信息
    editUserInfo(){
      this.$refs.editFormRef.validate(async valid =>{
        // console.log(valid);
        if(!valid) return;
        const res = await this.axios.put(`users/${this.editForm.id}`,
        {email:this.editForm.email,mobile:this.editForm.mobile});
        // console.log(res);
        const {status} = res.data.meta;
        if(status !== 200) return this.$message.error('更新用户失败');
        this.editDialogVisible = false;
        this.$message.success('更新用户成功~');
        
        this.getUserList()
      })
    },
    // 删除用户
    delUser(id){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.axios.delete(`users/${id}`);
        // console.log(res);
        const {status}  = res.data.meta;
        if(status !== 200) return this.$message.error('删除用户失败~')
        this.$message({
          type: 'success',
          message: '用户删除成功!'
        });
        this.getUserList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    // 分配用户角色
    async fenUser(uinfo){
      this.userInfo = uinfo;

      const {data: res} = await  this.axios.get('roles');
      if(res.meta.status !==200){
        return this.$message.error('分配角色失败了~');
      }
      // this.$message.success('分配角色成功~');
      this.roleslist = res.data;
      this.roleDialogVisible = true;
      // console.log(this.roleslist)
    },
    // 更新角色的对话框提交事件
    async saveRole(){
      if(!this.selectRoleid){
        return this.$message.error('请选择分配的角色~');
      }

      const {data:res} = await this.axios.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleid})
      if(res.meta.status !==200){
        return this.$message.error('更新角色失败了~');
      }
      this.$message.success('更新角色成功~');
      this.getUserList();
      // console.log(res);
      this.roleDialogVisible = false
    },
    // 更新角色的对话框关闭事件
    roleDialogClose(){
      this.selectRoleid = '',
      this.userInfo = {};
    }
  }
}
</script>

<style>

</style>